package com.test.daily.leetcode.y2021.m10.day1022;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @descriptions:
 * @author: Tom
 * @date: 2021/10/22 上午 10:51
 * @version: 1.0
 */
public class Code01_MajorityElement {
    public static void main(String[] args) {
        int[] nums = new int[]{0,0,0};
        List<Integer> ans = majorityElemet(nums);
        for (int element : ans) {
            System.out.print(element + " ");
        }
    }

    public static List<Integer> majorityElement(int[] nums) {
        int N = nums.length;
        HashMap<Integer, Integer> map = new HashMap<>();
        ArrayList<Integer> ans = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.get(nums[i]) == null) {
                map.put(nums[i], 1);
            } else {
                map.put(nums[i], map.get(nums[i]) + 1);
            }
            if (map.get(nums[i]) > N / 3) {
                if (!ans.contains(nums[i])) {
                    ans.add(nums[i]);
                }
                if (ans.size() > 1) {
                    break;
                }
            }
        }
        return ans;
    }

    public static List<Integer> majorityElemet(int[] nums) {
        int element1 = 0;
        int element2 = 0;
        int vote1 = 0;
        int vote2 = 0;
        for (int num : nums) {
            if (num == element1 && vote1 > 0) {
                vote1++;
            } else if (num == element2 && vote2 > 0) {
                vote2++;
            } else if (vote1 == 0) {
                element1 = num;
                vote1++;
            } else if (vote2 == 0) {
                element2 = num;
                vote2++;
            } else {
                vote1--;
                vote2--;
            }
        }
        int cnt1 = 0;
        int cnt2 = 0;
        for (int num : nums) {
            if(vote1 > 0 && num == element1){
                cnt1++;
            }
            if(vote2 > 0 &&num == element2){
                cnt2++;
            }
        }
        ArrayList<Integer> ans = new ArrayList<>();
        if(cnt1 > (nums.length /3)){
           ans.add(element1);
        }
        if(cnt2 > (nums.length /3)){
            ans.add(element2);
        }
        return ans;
    }
}
